package com.wk.springframework.beans.factory.support;

import com.wk.springframework.common.exception.BeanException;
import com.wk.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.util.Objects;

public class SimpleInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeanException {
        Class beanClass = beanDefinition.getBeanClass();
        Object instance = null;
        try {
            if (Objects.nonNull(ctor)) {
                instance = beanClass.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            } else {
                instance = beanClass.newInstance();
            }
        } catch (Exception e) {
            throw new BeanException(e.getMessage());
        }
        return instance;
    }

}
